﻿Imports System.Text.RegularExpressions
Imports DAL
Imports System.Linq
Public Class UcGestionBénéficiaireV2
    Private BeneficiaireSelectione As New Beneficiaire
    Private Edition As Boolean
    Private EditionAffinite As Boolean
    Private EditionContact As Boolean
    Private isloading As Boolean
    Public mode As Mode = 1
    Dim listeAffinite As New List(Of DAL.BeneficiaireAffinite)
    Public Event listeBene As EventHandler
    Public Event suppression As EventHandler
    Public Event modification As EventHandler
    Public Event annulation As eventhandler

    'fonction qui valide les informations avant de les envoyés à la BD
    Public Function Validation()
        Dim verif As Boolean = True
        ErrVal.Clear()
        'Vérification des date de début et fin de service
        If (DtpFin.Checked AndAlso DtpFin.Value < DtpDébut.Value) Then
            ErrVal.SetError(DtpDébut, "La date de fin ne peut pas être inférieure à la date de début de service")
            ErrVal.SetError(DtpFin, "La date de fin ne peut pas être inférieure à la date de début de service")
            verif = False
        End If

        'vérification du nom vide
        If (TxtNom.Text = "") Then
            ErrVal.SetError(TxtNom, "Veuillez entrer un nom")
            verif = False
        End If

        'vérification du prénom vide
        If (TxtPrenom.Text = "") Then
            ErrVal.SetError(TxtPrenom, "Veuillez entrer un prénom")
            verif = False
        End If

        If DtpNaiss.Value > Today Then
            ErrVal.SetError(DtpNaiss, "La date doit être inférieure à la journée actuelle")
            verif = False
            'Validation de l'insertion d'un bénéficiaire de plus de 119 ans
        ElseIf DtpNaiss.Value.Year < Today.Year - 120 AndAlso MsgBox("Êtes-vous sûr d'avoir un bénéficiaire de plus de 119 ans?", vbYesNo) = vbNo Then
            DtpNaiss.Value = Today
            verif = False
        End If

        'Si aucune erreur, ajout ou modification des infomations du bénéficiaire
        If verif = True Then
            Return True
        Else
            Return False
        End If
    End Function

    'fonction qui permet la création d'un nouveau bénéficiaire
    Public Sub Ajouter_Beneficiaire(ByVal sender As Object, ByVal e As System.EventArgs)
        Select Case mode
            'Lorsque l'utilisateur est en mode ajout, les champs sont vidés
            Case mode.ajout
                ViderChamps()
                'Lorsque l'utilisateur est en mode consultation, les champs sont vidés et un nouvel élément est créé
            Case mode.consultation
                ViderChamps()
                changerMode(mode.ajout)
                'Lorsque l'utilisateur est en mode edition, demande d'enregistrement des modifications et un nouvel élément est créé
            Case mode.edition
                If MsgBox("Voulez-vous enregistrer les modifications du bénéficiaire?", MsgBoxStyle.YesNo) = 6 Then
                    InsererBeneficiaire(Nothing, Nothing)
                    If mode.edition Then
                        Exit Sub
                    End If
                End If
                ViderChamps()
                changerMode(mode.ajout)
        End Select
    End Sub

    'fonction qui permet de supprimer un bénéficiaire
    Public Sub Enlever_Beneficiaire(ByVal sender As Object, ByVal e As System.EventArgs)
        Select Case mode
            Case mode.consultation
                If MsgBox("Êtes-vous sûr de vouloir supprimer le bénéficiaire?", MsgBoxStyle.YesNo) = 6 Then
                    BeneficiaireSelectione.Supprime = True
                    BeneficiaireSelectione.DateSupprime = Now
                    bd.SubmitChanges()
                    ViderChamps()
                    RaiseEvent listeBene("Rafraichir", Nothing)
                    changerMode(mode.consultation)
                End If
            Case mode.edition
                If MsgBox("Êtes-vous sûr de vouloir supprimer le bénéficiaire?", MsgBoxStyle.YesNo) = 6 Then
                    BeneficiaireSelectione.Supprime = True
                    BeneficiaireSelectione.DateSupprime = Now
                    bd.SubmitChanges()
                    ViderChamps()
                    RaiseEvent listeBene("Rafraichir", Nothing)
                    changerMode(mode.consultation)
                End If
        End Select
    End Sub

    Public Sub Annuler_Beneficiaire(ByVal sender As Object, ByVal e As System.EventArgs)
        Select Case mode
            Case mode.ajout
                ViderChamps()
            Case mode.edition
                AfficherBeneficiaire()
                changerMode(mode.consultation)
        End Select
        RaiseEvent modification(False, Nothing)
        RaiseEvent annulation(False, Nothing)
    End Sub

    ''Fonction permettant de valider les Adresses entrés
    'Private Function verifAdresse(ByVal test)
    '    Dim re As Regex = New Regex("^([\d]+)([\s])(.+)$")
    '    Return re.IsMatch(test)
    'End Function

    ''Fonction permettant de valider le code postal entré
    'Private Function VerifCP(ByVal test)
    '    Dim re As Regex = New Regex("^([^DdFfIiOoQqUuWwZz0-9\W])([0-9])([^DdFfIiOoQqUu0-9\W])\s([0-9])([^DdFfIiOoQqUu0-9\W])([0-9])$")
    '    Return re.IsMatch(test)
    'End Function

    'Gestion des boutons qui permettent d'afficher ou cacher les contrôles
    Private Sub GestionContrôle(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNote.Click, BtnAffinités.Click, BtnAccompagnement.Click, btnContact.Click
        CType(sender, Button).ImageIndex = IIf(CType(sender, Button).ImageIndex = 0, 1, 0)
        Select Case (sender.name)
            'bouton qui permet d'afficher ou cacher le contrôle Note
            Case ("BtnNote")
                RtxNotes.Visible = Not RtxNotes.Visible
                'bouton qui permet d'afficher ou cacher le contrôle Affinités
            Case ("BtnAffinités")
                TLPInterets.Visible = Not TLPInterets.Visible
                'bouton qui permet d'afficher ou cacher le contrôle Accompagnement
            Case ("BtnAccompagnement")
                LvAccompagnement.Visible = Not LvAccompagnement.Visible
                'bouton qui permet d'afficher ou cacher le contrôle Contact
            Case ("btnContact")
                UcGestionPersonneRessource1.Visible = Not UcGestionPersonneRessource1.Visible
        End Select
    End Sub
    Public Sub Onglets(ByVal mode As Boolean)
        BtnNote.ImageIndex = IIf(mode, 1, 0)
        BtnAffinités.ImageIndex = IIf(mode, 1, 0)
        BtnAccompagnement.ImageIndex = IIf(mode, 1, 0)
        btnContact.ImageIndex = IIf(mode, 1, 0)
        RtxNotes.Visible = mode
        TLPInterets.Visible = mode
        LvAccompagnement.Visible = mode
        UcGestionPersonneRessource1.Visible = mode

    End Sub
    ''Validation du format de code postal
    'Private Sub TbCodePostal_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtCodePostal.Leave
    '    If Not VerifCP(TxtCodePostal.Text) And Not TxtCodePostal.Text = "" Then
    '        ErrVal.SetError(TxtCodePostal, "Le code postal est invalide")
    '    Else
    '        ErrVal.SetError(sender, "")
    '    End If
    'End Sub

    'Validation de la date de naissance

    'Validation du format de l'adresse
    'Private Sub TbAdresse_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TxtAdresse.Leave
    '    If Not verifAdresse(TxtAdresse.Text) Then
    '        ErrVal.SetError(TxtAdresse, "L'adresse est invalide")
    '    Else
    '        ErrVal.SetError(sender, "")
    '    End If
    'End Sub

    Public Sub SelectionBeneficiaire(ByVal noBene As Integer)
        BeneficiaireSelectione = (From x In bd.Beneficiaires Where x.ID = noBene Select x).First
        isloading = True
        AfficherBeneficiaire()
        isloading = False
    End Sub

    'Affichage des données de bénéficiaire de la bd 
    Public Sub AfficherBeneficiaire()
        ViderChamps()
        changerMode(mode.consultation)
        With BeneficiaireSelectione
            TxtNom.Text = .Nom
            TxtPrenom.Text = .Prenom
            DtpNaiss.Value = IIf(Not .DateNaissance Is Nothing, .DateNaissance, Date.Now)
            ChkResident.Checked = IIf(Not .Resident Is Nothing, .Resident, False)
            TxtAdresse.Text = .Adresse
            If Not IsNothing(.Ville) Then CboVille.SelectedValue = .Ville
            TxtCodePostal.Text = .CodePostal
            Telephone1.SetTelephones(.Telephones.ToList)
            DtpDébut.Value = IIf(Not .DateDebut Is Nothing, .DateDebut, Date.Now)
            RtxNotes.Text = .Note
            listeAffinite = .BeneficiaireAffinites.ToList()
            UpdateListeAffinite()
            LvAccompagnement.Items.Clear()
            For Each x In (From i In .PlageHoraires Where i.Accompagnement = True And i.Date >= DateTime.Now Select i)
                Dim item As New ListViewItem
                item.Text = x.Employe1.Nom & ", " & x.Employe1.Prenom
                item.SubItems.Add(x.Date.ToShortDateString)
                LvAccompagnement.Items.Add(item)
            Next
            UcGestionPersonneRessource1.ListContact = .PersonneRessources.ToList
            UcGestionPersonneRessource1.IsOnLoad = True
            For Each contact In .PersonneRessources
                Dim item As New ListViewItem
                item.Text = contact.Nom + ", " + contact.Prenom
                item.Tag = contact.ID
                UcGestionPersonneRessource1.ListView1.Items.Add(item)
                UcGestionPersonneRessource1.ListContact.Add(contact)
            Next
            If UcGestionPersonneRessource1.ListView1.Items.Count = 0 Then
                UcGestionPersonneRessource1.viderChamps(False)
            Else
                UcGestionPersonneRessource1.ListView1.Items(0).Selected = True
            End If
            UcGestionPersonneRessource1.IsOnLoad = False
        End With
    End Sub

    'Creation d'un nouveau bénéficiaire
    Public Sub InsererBeneficiaire(ByVal sender As Object, ByVal e As System.EventArgs)
        If Validation() Then
            With BeneficiaireSelectione
                .Nom = StrConv(TxtNom.Text.Trim, VbStrConv.ProperCase)
                .Prenom = StrConv(TxtPrenom.Text.Trim, VbStrConv.ProperCase)
                .DateNaissance = DtpNaiss.Value
                .Resident = ChkResident.Checked
                .Adresse = TxtAdresse.Text
                .Ville1 = CboVille.SelectedItem
                .CodePostal = TxtCodePostal.Text
                Dim telephoneBen As New System.Data.Linq.EntitySet(Of Telephone)
                telephoneBen.AddRange(Telephone1.GetTelephones)
                .Telephones = telephoneBen
                .DateDebut = DtpDébut.Value
                Dim affiniteEmp As New System.Data.Linq.EntitySet(Of BeneficiaireAffinite)
                affiniteEmp.AddRange(listeAffinite)
                .BeneficiaireAffinites = affiniteEmp
                If DtpFin.Checked Then
                    .DateFin = DtpFin.Value
                Else
                    .DateFin = Nothing
                End If
                .Note = RtxNotes.Text
            End With
            Dim listeContact As New System.Data.Linq.EntitySet(Of PersonneRessource)
            listeContact.AddRange(UcGestionPersonneRessource1.ListContact)
            BeneficiaireSelectione.PersonneRessources = listeContact
            If BeneficiaireSelectione.ID = 0 Then
                bd.Beneficiaires.InsertOnSubmit(BeneficiaireSelectione)
            End If
            bd.SubmitChanges()
            Edition = False
            RaiseEvent listeBene("Rafraichir", Nothing)
            RaiseEvent listeBene(BeneficiaireSelectione.ID, Nothing)
            changerMode(mode.consultation)
        Else
            MsgBox("Certaines informations, sur le bénéficiaire, sont invalides")
        End If
    End Sub
    Private Sub UpdateListeAffinite()
        'Liste interets
        LvAffinite.Items.Clear()
        For Each a In listeAffinite
            Dim inte As New ListViewItem
            inte.Text = a.Affinite1.Nom
            inte.SubItems.Add(a.ID)
            LvAffinite.Items.Add(inte)
        Next
    End Sub
    'Insertion de données dans les listes de valeurs
    Private Sub UcGestionBénéficiaireV2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Me.DesignMode Then
            'villeBindingSource = bd.Villes
            'CboVille.DataSource = villeBindingSource
            Dim listVille As New List(Of Ville)
            For Each Ville In bd.Villes
                listVille.Add(Ville)
            Next
            CboVille.DataSource = listVille
            CboVille.DisplayMember = "Nom"
            CboVille.ValueMember = "ID"

            Dim listAffinite As New List(Of Affinite)
            For Each Affinite In bd.Affinites
                listAffinite.Add(Affinite)
            Next
            CboAffinités.DataSource = listAffinite
            CboAffinités.DisplayMember = "Nom"
            CboAffinités.ValueMember = "ID"

            Edition = False
            EditionAffinite = False
            EditionContact = False
        End If
    End Sub

    'Ajout d'affinite
    Private Sub GestionInteret(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAInterets.Click, BtnEInterets.Click
        If Not IsNothing(BeneficiaireSelectione) Then
            Select Case sender.name
                Case "BtnAInterets"
                    If Not CboAffinités.Text = String.Empty Then
                        If CboAffinités.SelectedIndex = -1 Then
                            Using nbd As New BDCarpeDiemDataContext
                                Dim nAff As New Affinite()
                                nAff.Nom = CboAffinités.Text
                                nbd.Affinites.InsertOnSubmit(nAff)
                                nbd.SubmitChanges()
                            End Using
                        End If
                        Dim aff As Affinite = (From x In bd.Affinites Where x.Nom = CboAffinités.Text Select x).First

                        For Each Inte In LvAffinite.Items
                            If Inte.text = CboAffinités.Text Then Exit Select
                        Next
                        Dim nEmpAff As New BeneficiaireAffinite()
                        nEmpAff.Affinite1 = aff

                        listeAffinite.Add(nEmpAff)
                        UpdateListeAffinite()
                        detecterChangement(True, Nothing)
                        CboAffinités.Text = ""
                    End If
                Case "BtnEInterets"
                    If LvAffinite.SelectedIndices.Count > 0 Then
                        detecterChangement(True, Nothing)

                        listeAffinite.RemoveAt(LvAffinite.SelectedIndices(0))
                        UpdateListeAffinite()
                    End If

            End Select
        Else

        End If
    End Sub

    'Enregistrement des affinite dans la bd
    Private Sub EnregistrementAffinite()
        bd.BeneficiaireAffinites.DeleteAllOnSubmit(From x In bd.BeneficiaireAffinites Where x.Beneficiaire = BeneficiaireSelectione.ID And Not (From i As ListViewItem In LvAffinite.Items Select i.Tag).Contains(x.Affinite) Select x)
        Dim aAjouters = From i As ListViewItem In LvAffinite.Items Where Not (From a In bd.BeneficiaireAffinites Where a.Beneficiaire = BeneficiaireSelectione.ID Select a.Affinite).Contains(i.Tag) Select i.Tag

        For Each aAjouter In aAjouters
            Dim affiniteAjouter As New BeneficiaireAffinite
            affiniteAjouter.Beneficiaire1 = BeneficiaireSelectione
            affiniteAjouter.Affinite = aAjouter
            bd.BeneficiaireAffinites.InsertOnSubmit(affiniteAjouter)
        Next
        EditionAffinite = False
    End Sub

    Public Sub changerMode(ByVal nmode As Integer)
        Static aMode As Mode = CarpeDiemHoraire.Mode.ajout

        Select Case aMode
            Case CarpeDiemHoraire.Mode.ajout

            Case CarpeDiemHoraire.Mode.edition

            Case CarpeDiemHoraire.Mode.consultation
        End Select

        Select Case nmode
            Case CarpeDiemHoraire.Mode.ajout
                BeneficiaireSelectione = New Beneficiaire
                RaiseEvent suppression(False, Nothing)
            Case CarpeDiemHoraire.Mode.edition

            Case CarpeDiemHoraire.Mode.consultation
                RaiseEvent modification(False, Nothing)
                RaiseEvent annulation(False, Nothing)
        End Select
        aMode = mode
        mode = nmode
    End Sub

    Public Sub recharger()
        Dim list As New List(Of Ville)
        For Each Ville In bd.Villes
            list.Add(Ville)
        Next
        CboVille.DataSource = list
        UcGestionPersonneRessource1.IsOnLoad = True
        UcGestionPersonneRessource1.cbVilleContact.DataSource = list
        UcGestionPersonneRessource1.IsOnLoad = False
    End Sub

    Public Sub RechargerAffinite()

        Dim listeAff As New List(Of Affinite)
        For Each Aff In bd.Affinites
            listeAff.Add(Aff)
        Next
        CboAffinités.DataSource = listeAff
    End Sub

    'Permet de détecter les changements dans les zones de texte (Textbox, DateTimePicker, Combobox...), radio, check
    'Ne détecte pas les , liste
    Private Sub detecterChangement(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtAdresse.TextChanged, TxtCodePostal.TextChanged, DtpNaiss.ValueChanged, CboVille.SelectedIndexChanged, DtpDébut.ValueChanged, DtpFin.ValueChanged,
        ChkResident.Click, RtxNotes.TextChanged, UcGestionPersonneRessource1.ajout, TxtNom.TextChanged, TxtPrenom.TextChanged
        If Not isloading Then
            RaiseEvent modification(True, Nothing)
            RaiseEvent annulation(True, Nothing)
            If mode = CarpeDiemHoraire.Mode.consultation Then changerMode(mode.edition)
        End If
    End Sub

    Public Sub ViderChamps()
        For Each iem In Tlp_Main.Controls
            Select Case True
                Case iem.name.substring(0, 3) = "TLP"
                    For Each item In iem.Controls
                        Select Case True
                            Case item.name.substring(0, 3) = "Txt" Or item.name.substring(0, 3) = "Dtp" Or item.name.substring(0, 3) = "Rtx"
                                item.text = ""
                            Case item.name.substring(0, 3) = "Rbo" Or item.name.substring(0, 3) = "Chk"
                                item.checked = False
                            Case item.name.substring(0, 2) = "Lv"
                                item.Items.clear()
                        End Select
                    Next
            End Select
        Next
        LvAffinite.Items.Clear()
        UcGestionPersonneRessource1.viderChamps(True)
        Telephone1.SetTelephones(BeneficiaireSelectione.Telephones.ToList)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim villeEnCour As Ville = CboVille.SelectedItem
        Dim villeEnCourC As Ville = UcGestionPersonneRessource1.cbVilleContact.SelectedItem
        Using villediag As New FrmGestionVille
            villediag.ShowDialog()
            recharger()
            If Not villeEnCour Is Nothing AndAlso CboVille.Items.Contains(villeEnCour) Then
                CboVille.SelectedItem = villeEnCour
            End If
            UcGestionPersonneRessource1.IsOnLoad = True
            If Not villeEnCourC Is Nothing AndAlso UcGestionPersonneRessource1.cbVilleContact.Items.Contains(villeEnCourC) Then
                UcGestionPersonneRessource1.cbVilleContact.SelectedItem = villeEnCourC
            End If
            UcGestionPersonneRessource1.IsOnLoad = False
        End Using
    End Sub

    Sub gererDroits()
        Select Case empConnecte.gestionBeneficiaire
            Case 1
                lectureSeule(True)
            Case 2
                lectureSeule(False)
        End Select
    End Sub

    Public Sub lectureSeule(ByVal mode As Boolean)
        For Each iem In Tlp_Main.Controls
            If iem.GetType() Is GetType(TableLayoutPanel) Then
                For Each item In iem.Controls
                    Select Case item.GetType()
                        Case GetType(TextBox)
                            CType(item, TextBox).ReadOnly = mode
                            CType(item, TextBox).ForeColor = Color.Black
                            CType(item, TextBox).BackColor = Color.White
                        Case GetType(DateTimePicker)
                            CType(item, DateTimePicker).Enabled = Not mode
                        Case GetType(CheckBox)
                            CType(item, CheckBox).Enabled = Not mode
                        Case GetType(RadioButton)
                            CType(item, RadioButton).Enabled = Not mode
                        Case GetType(ListView)
                            CType(item, ListView).Enabled = Not mode
                        Case GetType(ListBox)
                            CType(item, ListBox).Enabled = Not mode
                        Case GetType(PictureBox)
                            CType(item, PictureBox).Enabled = Not mode
                        Case GetType(ComboBox)
                            CType(item, ComboBox).Enabled = Not mode
                    End Select
                Next
            End If
        Next
        Button1.Enabled = Not mode
        Telephone1.Lecture = mode
        RtxNotes.Enabled = Not mode
        UcGestionPersonneRessource1.Enabled = Not mode
        BtnAInterets.Enabled = Not mode
        BtnEInterets.Enabled = Not mode
    End Sub
End Class

